/**
 * store_config.js
 * 全局Store统一配置入口
 */

// 导入第三方库
const { mobx } = require('../config/npm_config');
const { observable, action, runInAction, decorate } = mobx;

// 缓存组常量定义
const CACHE_GROUP = {
  PROJECT: 'project',
  TASK: 'task',
  USER: 'user',
  DOCUMENT: 'document',
  RESOURCE: 'resource',
  MEETING: 'meeting',
  CONFIG: 'config',
  SYSTEM: 'system',    // 系统缓存
  LIST: 'list',        // 列表数据缓存
  DETAIL: 'detail',    // 详情数据缓存
  TEMP: 'temp'         // 临时缓存
};

// 缓存优先级常量定义
const CACHE_PRIORITY = {
  HIGH: 3,    // 高优先级，最后清理
  NORMAL: 2,  // 普通优先级
  LOW: 1      // 低优先级，最先清理
};

// 内联定义ResourcesStore，避免循环依赖和路径问题
class ResourcesStore {
  // 状态定义
  loading = false;
  resources = {};
  cacheMap = new Map();
  
  // 缓存组常量，可以从外部访问
  CACHE_GROUP = CACHE_GROUP;
  
  // 缓存优先级常量
  CACHE_PRIORITY = CACHE_PRIORITY;
  
  // 缓存资源
  cacheResource(group, key, data) {
    if (!this.resources[group]) {
      runInAction(() => {
        this.resources[group] = {};
      });
    }
    
    runInAction(() => {
      this.resources[group][key] = data;
      // 记录缓存时间
      this.cacheMap.set(`${group}:${key}`, Date.now());
    });
    return data;
  }
  
  // 获取缓存资源
  getResource(group, key) {
    if (!this.resources[group] || this.resources[group][key] === undefined) {
      return null;
    }
    
    // 更新最后访问时间
    this.cacheMap.set(`${group}:${key}`, Date.now());
    return this.resources[group][key];
  }
  
  // 检查缓存是否存在
  hasResource(group, key) {
    return this.resources[group] && this.resources[group][key] !== undefined;
  }
  
  // 删除缓存
  removeResource(group, key) {
    if (this.resources[group] && this.resources[group][key] !== undefined) {
      delete this.resources[group][key];
      this.cacheMap.delete(`${group}:${key}`);
      return true;
    }
    return false;
  }
  
  // 清除指定组的所有缓存
  clearGroup(group) {
    if (this.resources[group]) {
      delete this.resources[group];
      // 清除相关的缓存映射
      for (const key of this.cacheMap.keys()) {
        if (key.startsWith(`${group}:`)) {
          this.cacheMap.delete(key);
        }
      }
      return true;
    }
    return false;
  }
  
  // 清除所有缓存
  clearAll() {
    runInAction(() => {
      this.resources = {};
      this.cacheMap.clear();
    });
  }
  
  // 清理过期缓存（超过10分钟的缓存）
  cleanExpired(maxAge = 10 * 60 * 1000) {
    const now = Date.now();
    const expiredKeys = [];
    
    // 找出所有过期的缓存
    for (const [key, time] of this.cacheMap.entries()) {
      if (now - time > maxAge) {
        expiredKeys.push(key);
      }
    }
    
    // 删除过期缓存
    for (const key of expiredKeys) {
      const [group, resourceKey] = key.split(':');
      if (this.resources[group] && this.resources[group][resourceKey]) {
        delete this.resources[group][resourceKey];
      }
      this.cacheMap.delete(key);
    }
    
    return expiredKeys.length;
  }
}

// 应用mobx装饰器
decorate(ResourcesStore, {
  loading: observable,
  resources: observable,
  cacheMap: observable,
  cacheResource: action,
  getResource: action,
  hasResource: action,
  removeResource: action,
  clearGroup: action,
  clearAll: action,
  cleanExpired: action
});

// 创建单例
const resourcesStore = new ResourcesStore();

// 尝试加载其他Store模块
let userStore = null;
let projectStore = null;
let taskStore = null;
let systemStore = null;

try {
  // 使用正确的模块路径 - 从模块目录加载index.js而非user_store.js
  const userModule = require('./modules/user/index');
  userStore = userModule.userStore || {};
} catch (error) {
  console.error('加载userStore失败，提供空实现', error);
  userStore = {};
}

try {
  // 直接使用modules目录中的project_store.js
  projectStore = require('./modules/project_store');
} catch (error) {
  console.error('加载projectStore失败，提供空实现', error);
  projectStore = {};
}

try {
  // 优先尝试直接使用modules目录中的task_store.js
  taskStore = require('./modules/task_store');
} catch (error) {
  // 如果直接引用失败，尝试从task子目录加载
  try {
    const taskModule = require('./modules/task/index');
    taskStore = taskModule.taskStore || {};
  } catch (innerError) {
    console.error('加载taskStore失败，提供空实现', innerError);
    taskStore = {};
  }
}

try {
  // 加载系统模块存储
  const systemModule = require('./modules/system/store_config');
  systemStore = systemModule || {};
} catch (error) {
  console.error('加载systemStore失败，提供空实现', error);
  systemStore = {};
}

// 导出所有Store
module.exports = {
  resourcesStore,
  userStore,
  projectStore,
  taskStore,
  systemStore,
  CACHE_GROUP,
  CACHE_PRIORITY
}; 